package water_qanxun_api.service.util;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import water_qanxun_api.dao.DevicesDao;
import water_qanxun_api.dao.DevicesDataDao;
import water_qanxun_api.domain.DevicesData;
import water_qanxun_api.domain.DevicesDataDomain;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class MyScheduledTask {
    
    @Autowired
    DevicesDao devicesDao;
    @Autowired
    DevicesDataDao devicesDataDomainDao;
    @Scheduled(fixedRate = 600000) // 10 minutes
    public void myTask() {
        System.out.println("myTask");
        LambdaQueryWrapper<DevicesData> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(DevicesData::getUid);
        List<DevicesData> devicesData = devicesDao.selectList(wrapper);
    
        for (DevicesData devicesData1 : devicesData) {
            LambdaQueryWrapper<DevicesDataDomain> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(DevicesDataDomain::getDeviceKey, devicesData1.getUid())
                    .orderByDesc(DevicesDataDomain::getTimestamp).
                    last("limit 100");
            List<DevicesDataDomain> devicesDataDomains = devicesDataDomainDao.selectList(wrapper1);
            if (devicesDataDomains.size() == 100) {
                List<DevicesDataDomain> subList = devicesDataDomains.subList(0, 100);
                List<Integer> ids = subList.stream().map(DevicesDataDomain::getId).collect(Collectors.toList());
                devicesDataDomainDao.delete(new QueryWrapper<DevicesDataDomain>().notIn("id", ids));
            }
        }
    }
}
